<template>
  <div style="margin-top: 5px">
    <div class="alert">
      <span><icon-exclamation-circle /></span>
      <span>所有按人员隔离数据的功能，按此处分配的成员来展示数据。</span>
    </div>
    <div>
      <a-select v-model="current" placeholder="请选择" @change="setCurrent">
        <a-option label="授权所有成员" :value="1"></a-option>
        <a-option label="授权本部门及子部门成员" :value="2"></a-option>
        <a-option label="授权指定成员" :value="3"></a-option>
      </a-select>
    </div>
    <div>
      <span v-if="current == 1" class="text-desc">开启授权所有将不能进行单个授权，且之后新增成员自动在授权范围内</span>
      <span v-if="current == 2" class="text-desc">开启授权本部门及子部门将不能进行单个授权，且之后加入到该部门成员自动在授权范围内</span>
      <span v-if="current == 3" class="text-desc">开启授权指定成员即可将以下指定成员在授权范围内</span>
    </div>
    <div v-if="current == 3">
      <div class="mt10" style="width: 300px">
        <a-space>
          <a-input placeholder="成员姓名" v-model="searchKey" :style="{ width: '180px' }" allow-clear />
          <!-- <a-button class="gray-outline">搜索</a-button> -->
          <a-button class="gray-outline" @click="setAuth">授权</a-button>
        </a-space>
      </div>
      <div class="table-space mt10">
        <div class="left">
          <a-scrollbar style="height: 380px; overflow: auto">
            <a-tree ref="tree" :data="treeData" multiple checkable :expanded-keys="expandedIds" :fieldNames="{ key: 'id' }" @check="selTreeItem"> </a-tree>
          </a-scrollbar>
        </div>

        <div class="right">
          <div class="top">
            <div>已授权成员</div>
            <div><a-button type="text" @click="cancelAuth('match')"> 批量取消授权</a-button></div>
          </div>
          <div class="bottom">
            <a-table size="mini" class="table-single-line" v-model:selected-keys="noSelIds" row-key="id" :data="selUserList" :pagination="false" :row-selection="rowSelection" :scroll="{ y: '380px' }">
              <template #columns>
                <a-table-column title="姓名" #cell="{ record }">
                  {{ record.userName }}
                </a-table-column>
                <a-table-column title="手机号" #cell="{ record }">
                  {{ record.mobile }}
                </a-table-column>
                <a-table-column title="所在部门" #cell="{ record }">
                  <TextLimit position="top" :rows="1">{{ record.deptName }}</TextLimit>
                </a-table-column>
                <a-table-column title="操作" #cell="{ record }" :width="70">
                  <a-button type="text" @click="cancelAuth('single', record)">取消授权</a-button>
                </a-table-column>
              </template>
            </a-table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, computed, watch, onMounted } from 'vue'
  import { saveOrUpdateFuncPermisson, getOrganizesWithUser } from '@/api/system'
  import FilterTable from '@/components/TableFilter.vue'
  import _ from 'lodash-es'
  import { Message } from '@arco-design/web-vue'
  import { nextTick } from 'vue'
  export default defineComponent({
    components: { FilterTable },
    props: ['userList', 'info', 'permissionList', 'roleId', 'ownId'],
    setup(props: any, { emit }) {
      const tree = ref()
      const data: any = reactive({
        selUserList: [],
        current: 3,
        selUserIds: [],
        rowSelection: {
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false,
        },
        noSelIds: [],
        searchKey: '',
        originTreeData: [],
        expandedIds: [],
        detailInfo: {},
        isParentIdList: [],
      })

      const treeData = computed(() => {
        if (!data.searchKey) return data.originTreeData
        return searchData(data.searchKey)
      })

      const searchData = (keyword: any) => {
        const loop = (data: any) => {
          const result: any = []
          data.forEach((item: any) => {
            if (item.title.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
              result.push({ ...item })
            } else if (item.children) {
              const filterData = loop(item.children)
              if (filterData.length) {
                result.push({
                  ...item,
                  children: filterData,
                })
              }
            }
          })
          return result
        }
        return loop(data.originTreeData)
      }

      const getMatchIndex = (title: string) => {
        if (!data.searchKey) return -1
        return title.toLowerCase().indexOf(data.searchKey.toLowerCase())
      }

      const setCurrent = async (step: string) => {
        data.current = step
        data.detailInfo.userConfig.level = step
        if (step != '3') {
          data.detailInfo.userConfig.level = step
          let params = {
            id: props.ownId,
            menuList: props.permissionList.menuList,
            roleId: props.roleId,
          }
          const res: any = await saveOrUpdateFuncPermisson([params])
          if (res) {
            Message.success('授权成功')
          }
        }
      }

      const getTreeUser = async () => {
        const res: any = await getOrganizesWithUser()
        let arr = res?.data || []
        assetsData(arr)
        data.originTreeData = arr
        console.log(data.originTreeData)
      }

      const assetsData = (item: any) => {
        item.forEach((e: any) => {
          if (e.children) {
            e.title = e.deptName
            e.key = e.id
            data.isParentIdList.push(e.id)
            data.expandedIds.push(e.id)
            e.userList.map((el: any) => {
              el.title = el.userName
              el.key = el.id
              data.expandedIds.push(el.id)
              return el
            })
            e.children = e.children.concat(e.userList)
            assetsData(e.children)
          }
        })
      }

      const initData = (item: any) => {
        data.detailInfo = item
        data.selUserList = []
        if (!data.detailInfo.userConfig) {
          let obj = {
            level: 3,
            userIdList: [],
          }
          data.detailInfo.userConfig = obj
        } else {
          data.current = data.detailInfo.userConfig.level
          let userId = data.detailInfo.userConfig.userIdList
          userId.forEach((e: any) => {
            let item: any = props.userList.find((el: any) => e == el.id)
            if (item) data.selUserList.push(item)
          })
        }
      }

      const selTreeItem = (list: any, item: any) => {
        list.forEach((e: any, i: number | string) => {
          let index = data.isParentIdList.findIndex((el: string) => e == el)
          if (index != -1) {
            list.splice(i, 1)
          }
        })
        data.selUserIds = list
      }

      const setAuth = async () => {
        if (!data.selUserIds[0]) {
          return Message.error('请选择成员')
        }
        data.detailInfo.userConfig.level = data.current
        data.detailInfo.userConfig.userIdList = [...data.selUserIds, ...data.detailInfo.userConfig.userIdList]
        savePer()
      }

      const cancelAuth = async (type: string, item?: any) => {
        if (type == 'match' && !data.noSelIds[0]) {
          return Message.error('请选择需要取消授权的用户')
        }
        let arr1 = new Set(data.detailInfo.userConfig.userIdList)
        let arr2 = type == 'match' ? new Set(data.noSelIds) : new Set([item.id])
        const differenceSet = new Set([...arr1].filter((x) => !arr2.has(x)))
        data.detailInfo.userConfig.userIdList = Array.from(differenceSet)
        console.log(data.detailInfo.userConfig.userIdList)

        savePer()
      }

      const savePer = async () => {
        let ids = data.detailInfo.userConfig.userIdList
        let arr = Array.from(new Set(ids))
        data.detailInfo.userConfig.userIdList = arr
        let params = {
          id: props.ownId,
          menuList: props.permissionList.menuList,
          roleId: props.roleId,
        }
        const res: any = await saveOrUpdateFuncPermisson([params])
        if (res) {
          Message.success('授权成功')
          tree.value.checkAll(false)
        }
        data.selIds = []
        data.noSelIds = []
      }

      watch(
        () => [props.userList, props.info],
        (val) => {
          setTimeout(() => {
            initData(val[1])
          }, 0)
        },
        { deep: true, immediate: true }
      )
      getTreeUser()
      return {
        ...(toRefs(data) as any),
        setCurrent,
        treeData,
        getMatchIndex,
        setAuth,
        selTreeItem,
        tree,
        cancelAuth,
      }
    },
  })
</script>

<style lang="less" scoped>
  .text-desc {
    color: #7f7f7f;
    font-size: 12px;
  }

  .alert {
    color: red;
    margin-bottom: 5px;
  }

  :deep(.arco-steps-item-title) {
    font-size: 14px;
  }

  :deep(.arco-steps-vertical .arco-steps-item:not(:last-child)) {
    min-height: 70px;
  }

  :deep(.arco-steps-item-finish .arco-steps-icon) {
    background-color: #f2f3f5;
  }

  :deep(.arco-steps-vertical .arco-steps-item:not(:last-child) .arco-steps-item-tail::after) {
    background-color: var(--color-neutral-3);
  }

  .table-space {
    width: 100%;
    display: flex;

    .left,
    .right {
      .top {
        padding: 0 10px;
        display: flex;
        justify-content: space-between;
        background-color: #f2f2f2;
        height: 40px;
        line-height: 40px;
        border-bottom: 1px solid #d7d7d7;
      }
      .bottom {
        padding: 3px;
        box-sizing: border-box;
      }
    }

    .left {
      width: 50%;
      border: 1px solid #d7d7d7;
      margin-right: 10px;
    }
    .right {
      flex: 1;
      border: 1px solid #d7d7d7;
    }
  }
</style>
